package com.pesking.core.sqlparser.processor;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.pesking.core.exception.SystemException;
import com.pesking.core.parameter.Parameter;
import com.pesking.core.sqlparser.parameter.SqlParameter;
import com.pesking.core.sqlparser.parameter.SqlParameterProcessor;

public class TimeSqlParameterHandler extends SqlParameterProcessor {

	@Override
	public String getTitle() {
		return "时间参数";
	}

	@Override
	public String getDescription() {
		return "设置时间参数,输入时间值为：hh:mm:ss或者hh:mm";
	}

	@Override
	public void handle(StringBuilder sbSQL, Parameter parameter, List<SqlParameter> processors,SqlParameter sqlParameter) {
		sbSQL.append("?");
		processors.add(sqlParameter);
	}


	@Override
	public void setParameter(PreparedStatement ps, Parameter parameter, int index,SqlParameter sqlParameter) throws SQLException {
		String value = parameter.getParameter(sqlParameter.getName());
		if (value != null && value.length() > 0 && !"null".equals(value))
		{
			String []pattern = {"hh:mm:ss","hh:mm"};
			Date objValue = null;
			for(int n = 0 ; n < pattern.length ; n++){
				SimpleDateFormat sdf = new SimpleDateFormat(pattern[n]);
				try{
					objValue= sdf.parse(value);							
					break;
				}
				catch(Exception ex){
					
				}
			}
			
			if (objValue == null){
				throw new SystemException("日期格式化错误：" + value);
			}
			
			ps.setTime(index, new java.sql.Time(objValue.getTime()));
		}
		else
		{
			ps.setNull(index, java.sql.Types.TIME);
		}
	}


	@Override
	public List<String> getSqlParameterType() {
		return Arrays.asList(new String []{"T","TIME"});
	}
}
